<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6" >
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input disabled v-model="model.code" placeholder="请输入编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="检验类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspectionType">
              <j-dict-select-tag type="list" v-model="model.inspectionType" dictCode="inspection_type" placeholder="请选择检验类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="入库单" :labelCol="labelCol" :wrapperCol="wrapperCol"  prop="storageCode">
              <a-input-search v-model="model.storageCode"
                              placeholder="请选择入库单"
                              @search="onSearchProcurement"></a-input-search>
              <!--                  <a-input v-model="row.procurementCode" disabled />-->
            </a-form-model-item>
<!--            <a-form-model-item label="入库单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storageId">-->
<!--              <j-dict-select-tag type="list" v-model="model.storageId" dictCode="buss_storage,code,id" placeholder="请选择入库单" />-->
<!--            </a-form-model-item>-->
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialName">
              <a-input v-model="model.materialName" disabled placeholder="请输入物料名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="物料来源" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialSource">
              <a-input v-model="model.materialSource" disabled placeholder="请输入物料来源" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerName">
              <a-input v-model="model.customerName" disabled placeholder="请输入客户名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplierName">
              <a-input v-model="model.supplierName" disabled placeholder="请输入供应商" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="检验标准" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="standardsId">
              <j-search-select-tag v-model="model.standardsId" @change="onChangeShowRow" dict="buss_inspection_standards,name,id" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="检验日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspectionDate">
              <j-date placeholder="请选择检验日期" v-model="model.inspectionDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="进厂日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterDate">
              <j-date placeholder="请选择进厂日期" disabled v-model="model.enterDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="抽检数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="samplingQuantity">
              <a-input-number v-model="model.samplingQuantity" :min="0" placeholder="请输入抽检数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="4" >
            <a-form-model-item label="批次号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="batchNum">
              <a-input v-model="model.batchNum" disabled placeholder="请输入批次号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="2" >
            <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unit">
              <j-dict-select-tag type="list" v-model="model.unit" dictCode="ji_unit" placeholder="请选择单位" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="批量(吨)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="batch">
              <a-input-number v-model="model.batch" disabled placeholder="请输入批量(吨)" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="物料批号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialLotNum">
              <a-input v-model="model.materialLotNum" disabled placeholder="请输入物料批号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="限用日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expiryDate">
              <j-date placeholder="请选择限用日期" disabled v-model="model.expiryDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="生产日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createDate">
              <j-date placeholder="请选择生产日期" disabled v-model="model.createDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="宝洁采购订单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjOrder">
              <a-input v-model="model.bjOrder" disabled placeholder="请输入宝洁采购订单号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="宝洁供应商编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjSupplierCode">
              <a-input v-model="model.bjSupplierCode" disabled placeholder="请输入宝洁供应商编码" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="宝洁供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bjSupplier">
              <a-input v-model="model.bjSupplier" disabled placeholder="请输入宝洁供应商" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-card title="入库明细">
          <a-tab-pane tab="检验单关联入库明细" :key="refKeys[0]" :forceRender="true">
            <j-vxe-table
              keep-source
              :ref="refKeys[0]"
              :loading="bussInspectionFormStorageTable.loading"
              :columns="bussInspectionFormStorageTable.columns"
              :dataSource="bussInspectionFormStorageTable.dataSource"
              @selectRowChange="handleTable1SelectRowChange"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="true"
              :toolbar="false"
            />
          </a-tab-pane>
          </a-card>
        </a-row>
        <a-row>
          <a-card title="质检明细">
          <a-tab-pane tab="质检明细" :key="refKeys[1]" :forceRender="true">
            <j-vxe-table
              keep-source
              :ref="refKeys[1]"
              :loading="bussInspectionFormDetailTable.loading"
              :columns="bussInspectionFormDetailTable.columns"
              :dataSource="bussInspectionFormDetailTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="false"
              :toolbar="false"
              @valueChange="handleValueChange"
            />
          </a-tab-pane>
          </a-card>
        </a-row>
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="检验结论" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspectionConclusion">
              <a-input v-model="model.inspectionConclusion" placeholder="请输入检验结论" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="检验结果" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspectionResults">
              <j-dict-select-tag type="radio" v-model="model.inspectionResults" dictCode="inspection_results" placeholder="请选择检验结果" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="检验员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspector">
              <j-search-select-tag v-model="model.inspector" dict="sys_user,realname,username" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
<!--    <a-tabs v-model="activeKey" @change="handleChangeTabs">-->
<!--      <a-tab-pane tab="检验单关联入库明细" :key="refKeys[0]" :forceRender="true">-->
<!--        <j-vxe-table-->
<!--          keep-source-->
<!--          :ref="refKeys[0]"-->
<!--          :loading="bussInspectionFormStorageTable.loading"-->
<!--          :columns="bussInspectionFormStorageTable.columns"-->
<!--          :dataSource="bussInspectionFormStorageTable.dataSource"-->
<!--          :maxHeight="300"-->
<!--          :disabled="formDisabled"-->
<!--          :rowNumber="true"-->
<!--          :rowSelection="true"-->
<!--          :toolbar="true"-->
<!--          />-->
<!--      </a-tab-pane>-->
<!--      <a-tab-pane tab="质检明细" :key="refKeys[1]" :forceRender="true">-->
<!--        <j-vxe-table-->
<!--          keep-source-->
<!--          :ref="refKeys[1]"-->
<!--          :loading="bussInspectionFormDetailTable.loading"-->
<!--          :columns="bussInspectionFormDetailTable.columns"-->
<!--          :dataSource="bussInspectionFormDetailTable.dataSource"-->
<!--          :maxHeight="300"-->
<!--          :disabled="formDisabled"-->
<!--          :rowNumber="true"-->
<!--          :rowSelection="true"-->
<!--          :toolbar="true"-->
<!--          />-->
<!--      </a-tab-pane>-->
<!--    </a-tabs>-->
    <buss-storage-list-modal ref="selectStorageList"
                             @storageOk="storageOk"
                             :category="category">

    </buss-storage-list-modal>
  </a-spin>
</template>

<script>

import { getAction, putAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import BussStorageListModal  from '@comp/base/modal/BussStorageListModal'
  import moment from 'dayjs'

  export default {
    name: 'BussInspectionFormForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
      BussStorageListModal
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
          style: 'width: 32%;',
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        category: '',
        model:{
          inspectionResults: '',
          selectedStorage: '',
          version: ''
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          inspectionType: [
            { required: true, message: '请选择检验类型!' }
          ],
          storageCode: [
            { required: true, message: '请选择入库单!' }
          ],
          inspectionResults: [
            { required: true, message: '请选择检验结果!' }
          ],
          inspector: [
            { required: true, message: '请选择检验员!' }
          ],
          standardsId: [
            { required: true, message: '请选择检验标准!' }
          ],
        },
        refKeys: ['bussInspectionFormStorage', 'bussInspectionFormDetail', ],
        tableKeys:['bussInspectionFormStorage', 'bussInspectionFormDetail', ],
        activeKey: 'bussInspectionFormStorage',
        // 检验单关联入库明细
        bussInspectionFormStorageTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '入库单编号',
              key: 'storageCode',
              width:"150px",
            },
            {
              title: '物料编号',
              key: 'materialCode',
              width: '120px',
            },
            {
              title: '物料名称',
              key: 'materialName',
              width: '150px',

            },
            {
              title: '单位',
              key: 'meUnit',
              type: JVXETypes.select,
              width: '80px',
              dictCode: 'ji_unit',
              disabled: true
            },
            {
              title: '规格',
              key: 'spec',
              width: '100px',
            },
            {
              title: '入库数量',
              key: 'num',
              width:"80px",
            },
            {
              title: '排产单号',
              key: 'schedulingNumber',
              width:"120px",
            },
            {
              title: '批量(吨)',
              key: 'batch',
              width:"80px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料来源',
              key: 'materialSource',
              width:"120px",
            },
            {
              title: '客户名称',
              key: 'customerName',
              width:"120px",
            },
            {
              title: '限用日期',
              key: 'expiryDate',
              width:"120px",
            },
            {
              title: '生产日期',
              key: 'createDate',
              width:"120px",
            },
          ]
        },
        // 质检明细
        bussInspectionFormDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '检验项目',
              key: 'inspectionItems',
              width:"200px",
            },
            {
              title: '检验标准',
              key: 'inspectionStandards',
              width:"200px",
            },
            {
              title: '标准类型',
              key: 'standardType',
              type: JVXETypes.select,
              dictCode:"standard_type",
              width:"120px",
              disabled: true
            },
            {
              title: '数值上限',
              key: 'upperLimit',
              width:"120px",
            },
            {
              title: '数值下限',
              key: 'lowerLimit',
              width:"120px",
            },
            {
              title: '检验数值',
              key: 'inspectionNumber',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '请输入${title}' }]
            },
            {
              title: '复检',
              key: 'reInspection',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '检验结果',
              key: 'inspectionResults',
              type: JVXETypes.select,
              options:[],
              dictCode:"jy_results",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/quality/bussInspectionForm/add",
          edit: "/quality/bussInspectionForm/edit",
          queryById: "/quality/bussInspectionForm/queryById",
          bussInspectionFormStorage: {
            list: '/quality/bussInspectionForm/queryBussInspectionFormStorageByMainId',
            detailList: '/quality/bussInspectionForm/queryBussStorageDetail'
          },
          bussInspectionFormDetail: {
            list: '/quality/bussInspectionForm/queryBussInspectionFormDetailByMainId',
            detailList: '/quality/bussInspectionForm/queryStandardsDetail'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    mounted() {
      this.$nextTick(() => {
        setTimeout(() => {
          console.log("1")
          this.checkAllRows();
        }, 1000);
        // 如果你需要在组件加载后执行，可以在这里调用

      });
    },
    methods: {
      getSequenceNum() {
        let url = "/sys/fillRule/executeRuleByCode/yclbcjyd";
        putAction(url, {}).then(res => {
          // 执行成功，获取返回的值，并赋到页面上
          if (res.success) {
            this.model.code = res.result;
          }
        })
      },
      checkAllRows() {
        const myTable = this.$refs.bussInspectionFormStorage;
        if (myTable) {
          myTable.setAllCheckboxRow(true);
          this.selectedRows = myTable.getCheckboxRecords();
          console.log(this.selectedRows);
        }
      },
      handleSelectAll({ selection, row }) {
        this.model.selectedStorage = '';
        const jeecgTable = this.$refs.bussInspectionFormStorage;
// 获取已勾选的行
        const selectedRows = jeecgTable.getCheckboxRecords();
        console.log(selectedRows);
        selectedRows.forEach(item => {
          if(!this.model.selectedStorage){
            this.model.selectedStorage = item.storageDetailId;
          }else {
            this.model.selectedStorage = this.model.selectedStorage + "," + item.storageDetailId;
          }
        })
        console.log(this.model.selectedStorage)
      },
      handleCheckboxChange({ row, checked, $table }) {
        this.model.selectedStorage = '';
        const jeecgTable = this.$refs.bussInspectionFormStorage;
// 获取已勾选的行
        const selectedRows = jeecgTable.getCheckboxRecords();
        console.log(selectedRows);
        selectedRows.forEach(item => {
          if(!this.model.selectedStorage){
            this.model.selectedStorage = item.storageDetailId;
          }else {
            this.model.selectedStorage = this.model.selectedStorage + "," + item.storageDetailId;
          }
        })
        console.log(this.model.selectedStorage)
      },
      handleValueChange({ row, column, value, oldValue }) {
        const field = column.property; // 变更列的字段名
        // 处理单元格数据变化的逻辑
        console.log(`Column ${column.title} changed from ${oldValue} to ${value}`);
        console.log(row);
        if(field === 'inspectionNumber') {
          if (row.standardType === '2') {
            if (row.inspectionNumber === '/') {
              row['inspectionResults'] = '1';
            }else {
              var min = parseFloat(row.lowerLimit);
              var max = parseFloat(row.upperLimit);
              var num = parseFloat(row.inspectionNumber);
              if (num >= min && num <= max) {
                row['inspectionResults'] = '1';
                // const index = this.bussInspectionFormDetailTable.dataSource.findIndex(item => item.id === rowData.id);
                // if (index !== -1) {
                //   this.bussInspectionFormDetailTable.dataSource[index]['inspectionResults'] = '1';
                // }
              } else {
                row['inspectionResults'] = '2';
              }
            }
          } else if (row.standardType === '1') {
            if (row.inspectionNumber === '合格' || row.inspectionNumber === '符合' || row.inspectionNumber === '/') {
              row['inspectionResults'] = '1';
            } else {
              row['inspectionResults'] = '2';
            }
          }
          //循环列表判断合格不合格
          this.onChangeInspectionResults();
        }
        if(field === 'reInspection') {
          if (row.standardType === '2') {
            if (row.reInspection === '/') {
              row['inspectionResults'] = '1';
            }else {
              var min = parseFloat(row.lowerLimit);
              var max = parseFloat(row.upperLimit);
              var num = parseFloat(row.reInspection);
              if (num >= min && num <= max) {
                row['inspectionResults'] = '1';
                // const index = this.bussInspectionFormDetailTable.dataSource.findIndex(item => item.id === rowData.id);
                // if (index !== -1) {
                //   this.bussInspectionFormDetailTable.dataSource[index]['inspectionResults'] = '1';
                // }
              } else {
                row['inspectionResults'] = '2';
              }
            }
          } else if (row.standardType === '1') {
            if (row.reInspection === '合格' || row.reInspection === '符合' || row.reInspection === '/') {
              row['inspectionResults'] = '1';
            } else {
              row['inspectionResults'] = '2';
            }
          }
          //循环列表判断合格不合格
          this.onChangeInspectionResults();
        }
      },
      onChangeInspectionResults() {
        var inspectionResults = '1';
        for(let i=0; i<this.bussInspectionFormDetailTable.dataSource.length; i++){
          let info = this.bussInspectionFormDetailTable.dataSource[i]
          console.log(i+info.inspectionResults);
          if(!info.inspectionResults) {
            inspectionResults = '';
            break;
          }else {
            if(info.inspectionResults === '2') {
              inspectionResults = '2';
            }
          }
        }
        console.log(inspectionResults);
        this.model.inspectionResults = inspectionResults;
        console.log(this.model.inspectionResults);
      },
      onChangeShowRow() {
        console.log(this.model.standardsId)
        let params = { id: this.model.standardsId }
        this.requestSubTableData(this.url.bussInspectionFormDetail.detailList, params, this.bussInspectionFormDetailTable)
      },
      onSearchProcurement(){
        // 采购订单
        this.$nextTick(() => {
          this.$refs.selectStorageList.add();
        })
      },
      storageOk(res) {
        console.log("123")
        console.log(res)
        this.model.storageCode = res.code;
        this.model.supplierName = res.supplierName;
        this.model.storageId = res.id;
        this.model.supplierId = res.supplierId;
        this.model.inspectionDate = moment(new Date()).format('YYYY-MM-DD');
        this.model.enterDate = res.warehouseDate;
        this.model.batchNum = res.batchNum;
        this.model.materialLotNum = res.materialLotNum;
        this.model.materialName = res.materialName;
        this.model.materialId = res.materialId;
        this.model.createDate = res.createDate;
        this.model.expiryDate = res.expiryDate;
        this.model.enterDate = res.warehouseDate;
        this.model.bjOrder = res.bjProcurementCode;
        this.model.bjSupplierCode = res.bjSupplierCode;
        this.model.bjSupplier = res.bjSupplierName;
        this.model.version = res.version;
        let params = { id: res.id , materialId : res.materialId}
        this.requestSubTableData(this.url.bussInspectionFormStorage.detailList, params, this.bussInspectionFormStorageTable)
        setTimeout(() => {
          console.log("1")
          this.checkAllRows();
        }, 1000);
      },
      addBefore(){
        this.bussInspectionFormStorageTable.dataSource=[]
        this.bussInspectionFormDetailTable.dataSource=[]
        this.getSequenceNum()
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.bussInspectionFormStorage.list, params, this.bussInspectionFormStorageTable)
          this.requestSubTableData(this.url.bussInspectionFormDetail.list, params, this.bussInspectionFormDetailTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          bussInspectionFormStorageList: this.selectedRows,
          bussInspectionFormDetailList: allValues.tablesValue[1].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      handleTable1SelectRowChange(event) {
        let {row, action, selectedRows, $table} = event;
        this.selectedRows = selectedRows;
        console.log(this.selectedRows)
      },
    }
  }
</script>

<style scoped>
</style>